package com.xuhj.controller;

import com.xuhj.pojo.Dept;
import com.xuhj.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
 * @Author xuhj
 * @Description 提供Rest服务，一个微服务不管是不是web服务，都必须要写Controller，提供给别人调用的！！！！
 * @Date 10:44 下午 2021/7/28
 * @Param
 * @return
 **/
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient client;

    /**
     * @RequestBody 必须要加，因为post请求在进行微服务调用的时候是在请求体中的，所以必须要在请求体里面取值，默认是从url追加的里面取值的
     * ！！！！！！！！！！
     */
    @PostMapping(value = "/dept/add",produces = "application/json;charset=UTF-8")
    public boolean addDept(@RequestBody Dept dept) {
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{deptno}")
    public Dept queryDeptById(@PathVariable("deptno") long deptno) {
        return deptService.queryDeptById(deptno);
    }

    @GetMapping("/dept/list")
    public List<Dept> queryAllDept() {
        return deptService.getAllDept();
    }

    /**
     * 获取微服务的一些信息,服务联调用
     */
    @RequestMapping("/dept/discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("discovery => services:" + services);
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT_8001");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri() + "\t" +
                    instance.getInstanceId() + "\t" +
                    instance.getServiceId() + "\t" +
                    instance.getMetadata());
        }
        return this.client;
    }
}
